package com.hc.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hc.ex.VerifyCodeException;
import com.hc.utils.GlobalConstant;
import com.hc.utils.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 *
 * @author 梁云亮
 */
@Component
public class VerifyCodeFilter extends OncePerRequestFilter {

	@Resource
	private RedisUtil redisUtil;

	@Resource
	LoginFailureHandler loginFailureHandler;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String url = request.getRequestURI();
		//拦截login请求
		if (url != null && url.contains("/login") && request.getMethod().equals("POST")) {
			try{
				validate(request);	// 校验验证码
			} catch (VerifyCodeException e) {
				loginFailureHandler.onAuthenticationFailure(request, response, e);	// 校验失败，交给认证失败处理器
			}
		}
		filterChain.doFilter(request, response);
	}

	// 校验验证码逻辑
	private void validate(HttpServletRequest request) {
		String key = request.getParameter("key");
		String code = request.getParameter("code");

		if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
			throw new VerifyCodeException("验证码错误");
		}

		if (!code.equals(redisUtil.hget(GlobalConstant.VERIFYCODE_KEY, key))) {
			throw new VerifyCodeException("验证码错误");
		}

		// 一次性使用： 使用之后删除
		redisUtil.hdel(GlobalConstant.VERIFYCODE_KEY, key);
	}
}
